package oct2013.linkednode;

public class RotateList {
	public ListNode rotateRight(ListNode head, int n) {
		int len = 0;
		ListNode cur = head;
		while (cur != null) {
			len++;
			cur = cur.next;
		}
		if (len == 0)
			return head;
		return rotate(head, n % len);
	}

	ListNode rotate(ListNode head, int k) {
		if (k == 0)
			return head;
		ListNode tail1 = head;
		ListNode tail2 = head;
		while (k > 0) {
			tail2 = tail2.next;
		}
		while (tail2.next != null) {
			tail2 = tail2.next;
			tail1 = tail1.next;
		}
		tail2.next = head;
		head = tail1.next;
		tail1.next = null;
		return head;
	}
}
